package com.hgb.mall.admin.services.impl;

import com.github.pagehelper.PageHelper;
import com.hgb.mall.admin.services.SmsHomeRecommendProductService;
import com.hgb.mall.mbg.entity.SmsHomeRecommendProduct;
import com.hgb.mall.mbg.mapper.SmsHomeRecommendProductDynamicSqlSupport;
import com.hgb.mall.mbg.mapper.SmsHomeRecommendProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static org.mybatis.dynamic.sql.SqlBuilder.*;

/**
 * 首页人气推荐管理Service实现类
 * Created by hgb on 2020/11/7.
 */
@Service
public class SmsHomeRecommendProductServiceImpl implements SmsHomeRecommendProductService {
    @Autowired
    private SmsHomeRecommendProductMapper recommendProductMapper;

    @Override
    public int create(List<SmsHomeRecommendProduct> homeRecommendProductList) {
        for (SmsHomeRecommendProduct recommendProduct : homeRecommendProductList) {
            recommendProduct.setRecommendStatus(1);
            recommendProduct.setSort(0);
            recommendProductMapper.insert(recommendProduct);
        }
        return homeRecommendProductList.size();
    }

    @Override
    public int updateSort(Long id, Integer sort) {
        SmsHomeRecommendProduct recommendProduct = new SmsHomeRecommendProduct();
        recommendProduct.setId(id);
        recommendProduct.setSort(sort);
        return recommendProductMapper.updateByPrimaryKeySelective(recommendProduct);
    }

    @Override
    public int delete(List<Long> ids) {

        return recommendProductMapper.delete(c -> c.where(SmsHomeRecommendProductDynamicSqlSupport.id, isIn(ids)));
    }

    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {

        return recommendProductMapper.update(r -> r
                .set(SmsHomeRecommendProductDynamicSqlSupport.recommendStatus).equalTo(recommendStatus)
                .where(SmsHomeRecommendProductDynamicSqlSupport.id, isIn(ids)));
    }

    @Override
    public List<SmsHomeRecommendProduct> list(String productName, Integer recommendStatus, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);

        return recommendProductMapper.select(c -> c
                .where(SmsHomeRecommendProductDynamicSqlSupport.productName, isLikeWhenPresent(productName)
                        .then(s -> "%" + s + "%"))
                .and(SmsHomeRecommendProductDynamicSqlSupport.recommendStatus, isEqualToWhenPresent(recommendStatus))
                .orderBy(SmsHomeRecommendProductDynamicSqlSupport.sort.descending()));
    }
}
